package com.bf.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

@Slf4j
public class BfThreadPoolNoReturnUtils extends BfThreadPoolCommon {
    //无返回值子任务(子任务有方法名)
    private CopyOnWriteArrayList<Map<String, Object>> consumersName = new CopyOnWriteArrayList<>();
    // 是否开启主线程等待子线程执行完成
    protected Boolean ifMainThreadAwait = false;
    protected long timeout = 120L;
    protected TimeUnit unit = TimeUnit.SECONDS;

    public BfThreadPoolNoReturnUtils(String jobName) {
        this.jobName = jobName;
    }

    public BfThreadPoolNoReturnUtils() {
    }

    /**
     * 执行无返回方法
     */
    public void run() {
        CountDownLatch latch = new CountDownLatch(consumersName.size());

        initialize();

        for (int i = 0; i < consumersName.size(); i++) {
            int finalI = i;
            // 执行方法
            threadPoolExecutor.execute(() -> {
                Consumer<Integer> integerConsumer = (Consumer<Integer>) consumersName.get(finalI).get("method");
                try {
                    integerConsumer.accept(finalI);
                } catch (Exception e) {
                    log.error("子任务{}执行异常：{}", consumersName.get(finalI).get("name"), e.getMessage());
                    throw e;
                } finally {
                    if (ifMainThreadAwait) {
                        latch.countDown();
                    }
                }
            });
        }
        // 进行主线程等待
        if (ifMainThreadAwait) {
            try {
                // 主线程等待所有任务完成
                boolean await = latch.await(timeout, unit);
                if (!await) {
                    log.error("任务{}执行失败！", jobName);
                }
            } catch (Exception e) {
                log.error("任务{}等待超时", jobName);
                e.printStackTrace();
            }
        }
    }

    /**
     * 添加无返回值任务
     */
    public BfThreadPoolNoReturnUtils addConsumers(Consumer<Integer> consumer, String name) {
        consumersName.add(new HashMap<String, Object>() {{
            put("method", consumer);
            put("name", name);
        }});
        return this;
    }
}
